/**
 * 回调函数
 */

const blogRouterHandle = require('./router/blog')
const userRouterHandle = require('./router/user')
const { setRedis, getRedis } = require('./exec/execRedis')

const getPostData = (req) => {
    const method = req.method
    const contentType = req.headers['content-type']
    const promise = new Promise((resolve, reject) => {
        if (method !== 'POST' || contentType !== 'application/json') {
            resolve({})
            return
        }
        let postData = ''
        req.on('data', (chunk) => {
            postData += chunk
        })
        req.on('end', () => {
            if (!postData) {
                resolve({})
                return
            }
            resolve(JSON.parse(postData))
        })
    })

    return promise
}


const serverHandle = (req, res) => {
    // 设置返回的头部数据格式
    res.setHeader('Content-type', 'application/json')
    // 解析cookie
    let cookie = {}
    let cookieStr = req.headers['cookie'] || ''
    let cookieArr = cookieStr.split('; ')
    cookieArr.forEach(item => {
        if (!item) return
        let key = item.split('=')[0]
        let val = item.split('=')[1]
        cookie[key] = val
    })
    req.cookie = cookie
    let userId = req.cookie.userId || ''
    if (!userId) {
        userId = `${Date.now()}_${Math.random()}`
        setRedis(userId, {})
    }
    req.userId = userId
    getRedis(userId).then(redisStr => {
        if (!redisStr) {
            setRedis(userId, {})
            req.session = {}
        } else {
            req.session = JSON.parse(redisStr)
        }
        return getPostData(req)
    }).then(postData => {
        req.body = postData
        const blogPromise = blogRouterHandle(req, res)
        if (blogPromise) {
            blogPromise.then(sqlData => {
                res.end(JSON.stringify(sqlData))
            })
            return
        }
        const userPromise = userRouterHandle(req, res)
        if (userPromise) {
            userPromise.then(sqlData => {
                res.end(JSON.stringify(sqlData))
            })
            return
        }
        res.writeHead(404, {'Content-type': 'text/plain'})
        res.write('404 NOT FOUND')
        res.end()
    })
}

module.exports = serverHandle